<?php

namespace Modules\Chat\Service;

use App\Helper\LogHelper;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Modules\Chat\Base\BaseService;
use Modules\Chat\Models\ChatUser;

class MessageService extends BaseService
{

    public function sendMessageText($message, $room_id, $user_id, $keytype)
    {
        // 消息数据
        $content['content'] = $message;

        $user = ChatUser::find($user_id);

        $messageData = json_encode([
            'content' => $content,
            'keytype' => $keytype,
            'user' => $user,
            'uid' => $user->id,
            'guid' => $chat_message->id,
        ]);

        $result = $this->curl($messageData);
        LogHelper::info('result', $result);

        return $result;
    }

    private function curl($data)
    {
        LogHelper::info('data', $data);
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, "http://127.0.0.1:9502");
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_HEADER, 1);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_exec($curl);
        curl_close($curl);

        LogHelper::info('curl', $curl);
    }

    /**
     * 主动触发
     */
    public function activepush()
    {
        $message['message'] = "我是PHP-client端,发来的消息3";
        $message['user_id'] = 1;
        $message['room_id'] = 1;
        $message['type'] = 'message';

        $message2 = [
            'content' => '我是PHP-client端,发来的消息',
            'user_id' => 1,
            'room_id' => 1,
            'created_at' => time()
        ];
//        Message::create($message2);
//        $a = $this->curl(json_encode($message));   // 主动推送消息
        $messageData['data'] = json_encode($message);
        $a = $this->curl($messageData);   // 主动推送消息
        LogHelper::info('curlReturn', $a);
    }
}
